package com.example.flowable.expense.controller;

import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.common.impl.identity.Authentication;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.form.api.FormDeployment;
import org.flowable.form.api.FormRepositoryService;
import org.flowable.form.engine.FormEngine;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author Foolish
 * @description
 * @date: 2018/9/4 16:03
 */

@Controller
@RequestMapping(value = "expense")
public class ExpenseController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private FormEngine formEngine;

    /**
     * 部署报销流程
     */
    @RequestMapping(value = "deploy")
    @ResponseBody
    public String deploy() {
        //部署流程
        Deployment deployment = repositoryService.createDeployment()
                .name("报销流程")
                .addClasspathResource("flowable/ExpenseProcess.bpmn20.xml")
                .deploy();
         return "部署成功.流程Id为：" + deployment.getId();
    }

    /**
     * 添加报销
     *
     * @param taskUser    用户Id
     * @param money     报销金额
     */
    @RequestMapping(value = "add")
    @ResponseBody
    public String addExpense(String taskUser, Integer money, String processDefinitionKey) {
        //启动流程
        HashMap<String, Object> map = new HashMap<>();
        map.put("taskUser", taskUser);
        map.put("money", money);
        Authentication.setAuthenticatedUserId("Foolish");
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinitionKey, map);
        Authentication.setAuthenticatedUserId(null);
        return "提交成功.流程实例Id为：" + processInstance.getId();
    }

    /**
     * 获取审批管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String userId) {
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(userId).orderByTaskCreateTime().desc().list();
        for (Task task : tasks) {
            System.out.println(task.toString());
        }
        return tasks.toArray().toString();
    }

    /**
     * 批准
     *
     * @param taskId 任务ID
     */
    @RequestMapping(value = "apply")
    @ResponseBody
    public String apply(String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            throw new RuntimeException("流程不存在");
        }
        //通过审核
        HashMap<String, Object> map = new HashMap<>();
        map.put("outcome", "通过");
        taskService.complete(taskId, map);
        return "processed ok!";
    }

    /**
     * 拒绝
     */
    @ResponseBody
    @RequestMapping(value = "reject")
    public String reject(String taskId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("outcome", "驳回");
        taskService.complete(taskId, map);
        return "reject";
    }

    /**
     * 注册表单
     */
    @ResponseBody
    @RequestMapping(value = "form/add")
    public String formAdd() {
        FormRepositoryService frs = formEngine.getFormRepositoryService();

        String resource = "form/test.form";

        FormDeployment deploy = frs.createDeployment()
                .addClasspathResource(resource)
                .deploy();

        System.out.println(deploy);
        return deploy.toString();
    }

    /**
     * 新建带表单的流程
     */
    @ResponseBody
    @RequestMapping(value = "form/binding")
    public String formBinding(String deploymentId) {
        FormRepositoryService frs = formEngine.getFormRepositoryService();
        RepositoryService rs = processEngine.getRepositoryService();
        //id查询流程
        Deployment deploy = rs.createDeploymentQuery().deploymentId("taskId").singleResult();

        //id查询表单
        FormDeployment formDeploy = frs.createDeploymentQuery()
                .deploymentId(deploymentId).singleResult();


        frs.createDeployment().addClasspathResource("")
                .parentDeploymentId(deploy.getId())

                .deploy();

        System.out.println(formDeploy);
        System.out.println(deploy);
        return deploy.toString();
    }
}
